package com.woniumall.filter;

import com.woniumall.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther linke
 * @create 2021-11-05 21:47
 */
@WebFilter(urlPatterns = {"/personal/*","/address/*"})
public class UserCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 转型为与协议相关对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //转型为协议相关响应对象
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        User user = (User)httpServletRequest.getSession().getAttribute("user");//获取user对象

        if(user == null){//如果user对象为空则跳转至首页登录
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/user/login.jsp");
        }else{
            chain.doFilter(httpServletRequest,httpServletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
